<template>
  <div class="cjui-dynamic-form-parser">
    <el-form 
      :model="formData"
      :label-position="baseFormComponent.property.labelPosition"
      :label-width="baseFormComponent.property.labelWidth"
      :size="baseFormComponent.property.size"
    >
      <el-row>
        <el-col
          v-for="element in pageComponents"
          :key="element.uid || element.id"
          :span="element.property.__config__.span"
        >
          <el-form-item
            :label="element.property.__config__.label"
            :label-width="element.property.__config__.labelWidth"
          >
            <component
              :is="components[element.id]"
              :property="element.property"
              :style="{ width: element.property.__config__.width }"
              v-bind="element.property.__attr__"
              v-model="formData[element.property.__config__.model]"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import _ from 'lodash-es'
import { FormConfigSubmit } from './types'
import { FormConfigBuild } from './utils'
import { components, DiyComponent, usePropertyForm } from './components/index'
import {
  FormConfigBaseInfo,
  component as baseInfoComponentRefer,
} from './components/BaseInfo/config'
import {
  FormConfigBaseForm,
  component as baseFormComponentRefer,
} from './components/BaseForm/config'

defineOptions({
  name: 'CjuiDynamicFormParser'
})

interface Props {
  modelValue: object
  formConfig: FormConfigSubmit | undefined
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: undefined,
  formConfig: undefined
})
const emit = defineEmits(['update:modelValue'])
const { formData } = usePropertyForm(props.modelValue, emit)

// 基础设置组件
const baseInfoComponent = ref<DiyComponent<FormConfigBaseInfo>>(
  _.cloneDeep(baseInfoComponentRefer),
)
// 表单容器组件
const baseFormComponent = ref<DiyComponent<FormConfigBaseForm>>(
  _.cloneDeep(baseFormComponentRefer),
)
// 组件列表
const pageComponents = ref<DiyComponent<any>[]>([])

function initFormConfig() {
  const formConfig = new FormConfigBuild(props.formConfig)
  baseInfoComponent.value.property = formConfig
  baseFormComponent.value.property = formConfig.configJson
  pageComponents.value = formConfig.configJson.fields
  console.log('initFormConfiginitFormConfig', pageComponents.value)
}

onMounted(() => {
  initFormConfig()
})
</script>

<script lang="ts" setup></script>

<style lang="scss">
</style>
